<?php

namespace App\Http\Controllers;

use App\Models\Org;
use App\Models\SmsCode;
use App\Models\Team;
use App\Models\TeamCashInfo;
use App\User;
use Carbon\Carbon;
use EasyWeChat\Core\Exception;
use Hashids\Hashids;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Facades\Excel;


class TeamCashInfoController extends Controller
{
    public function index(Request $request) {
        $user = $request->user();
        $node = TeamCashInfo::with('org', 'team.user', 'team');
        $perPage = $request->get('perPage', 10);
        $verifyStats = $request->get('verify_status', null);
        $keyword = $request->get('keyword', null);
        $asExcel = $request->get('asExcel', null);

        if($user->type == 3)
        {
            $node->where('org_id', $user->org_id);
        }elseif($user->type == 4)
        {

        }else{
            throw new \Exception('权限不足');
        }

        if($verifyStats === 0 || $verifyStats)
        {
//            dd($verifyStats);

            $node->where('verify_status', $verifyStats);
        }

        if ($keyword) {
            $node->where(function($query) use ($keyword){
                $query->where('contacts_phone', 'like', "%{$keyword}%")
                    ->orwhere('bank_card_num', 'like', "%{$keyword}%")
                    ->orWhereHas('team.user', function($query) use ($keyword) {
                        $query->where('username', 'like', "%{$keyword}%");
                    })
                    ->orWhereHas('team', function($query) use ($keyword) {
                        $query->where('name', 'like', "%{$keyword}%");
                });
            });
        }

        $node->orderByRaw("(case when verify_status=0 then 1 ELSE 2 END)");
        $node->orderBy('id', 'desc');
//        dd($node->toSql());

        if($asExcel){
            // 保持和分页的结构一致，设置data=>{}
            $tmp = $node->get()->toArray();
            $info = array(
                'data' => $tmp
            );
        }else {
            $info = $node->paginate($perPage)->toArray();
        }

        $res = $info['data'];

        if($asExcel){
            Excel::create(time(),function($excel) use ($res){

                $excel->sheet('volunteer', function($sheet) use ($res){
                    $sheet->appendRow(1, array(
                        '用户名', '团队名称', '姓名', '邮箱', '手机号', '身份证号', '账号性质', '户名',
                        '账户号', '开户银行', '开户支行', '开户行地址', '开户行联行号',
                    ));

                    for ($i = 0;$i<count($res);$i++){
                        $tmp = $res[$i];
                        $sheet->appendRow($i+2,array(
                            $tmp['team']['user']['username'], $tmp['team']['name'],
                            $tmp['contacts_realname'], $tmp['contacts_email'], $tmp['contacts_phone'],
                            $tmp['contacts_idno'] ? substr($tmp['contacts_idno'], 0, 6).'xxxxxxxx'.substr($tmp['contacts_idno'], -4) : '',
                            $tmp['bank_card_type'] == 1 ? '个人账号' : '对公账号' ,
                            $tmp['bank_card_account'], $tmp['bank_card_num'],
                            $tmp['bank_company'], $tmp['bank_branch'], $tmp['bank_card_open_addr'],  $tmp['bank_connect_code']));
                    }
                });
            })->export('xls');
        }

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);

    }

    public function show(Request $request, $id) {
        $user = $request->user();

        $cashInfo = TeamCashInfo::findorfail($id);

        if($user->type == 3)
        {
            if($cashInfo->org_id != $user->org_id)
            {
                return $this->returnJSON(null, 0, '权限错误');
            }
        }elseif($user->type == 4)
        {

        }else{
            throw new \Exception('权限不足');
        }

        return $this->returnJSON($cashInfo, 0, 'ok');
    }

    public function store(Request $request) {

        $user = $request->user();

        if($user->type != 2)
        {
            throw new \Exception('权限不足');
        }

        $node = TeamCashInfo::where('team_id', $user->team_id)->first();

        $isNew = empty($node)? true:false;
        $node = empty($node)? new TeamCashInfo():$node;


        $this->validate($request, [
            'contacts_realname' => 'required|max:32',
            'contacts_email' => 'required|max:255|email',
            'phone' => 'required|max:32',
            'contacts_idno' => 'required|max:18',
            'contacts_id_card_front' => 'required|max:255',
            'contacts_id_card_back' => 'required|max:255',
            'contacts_id_card_people' => 'required|max:255',
            'bank_card_account' => 'required',
            'bank_card_type' => 'required',
            'bank_card_num' => 'required|max:64',
            'bank_branch' => 'required|max:225',
            'bank_card_open_addr' => 'required|max:225',
            'bank_connect_code' => 'required|max:225',
            'bank_company' => 'required|max:225',
            'auth_document' => 'required|max:225',
        ]);

        $verifyCode = $request->input('code');
        $phone = $request->input('phone');
        //检查验证码
        $checkSms = SmsCode::checkVerifyCode($phone, $verifyCode, 1);
        if( !$checkSms )
        {
            return $this->returnJSON(null, 10001, '短信验证码错误,请重新输入');
        }

//        dd($phone, $verifyCode);

        $data = $request->only([
            'contacts_realname',
            'contacts_email',
            'contacts_phone',
            'contacts_idno',
            'contacts_id_card_front',
            'contacts_id_card_back',
            'contacts_id_card_people',
            'bank_card_type',
            'bank_card_account',
            'bank_card_num',
            'bank_company',
            'bank_branch',
            'bank_card_open_addr',
            'bank_connect_code',
            'auth_document',
        ]);
        $data['verify_status'] = 0;
        $data['team_id'] = $user->team_id;
        $data['org_id'] = $user->org_id;
        $data['contacts_phone'] = $request->get('phone');

        $node->fill($data);

        if($node->save())
        {

            return $this->returnJSON(null, 0, $isNew? '新增成功':'修改成功');
        }
        return $this->returnJSON(null, 500, '新建失败');
    }

    public function update(Request $request, $id)
    {
        $user = $request->user();
        $cashInfo = TeamCashInfo::findorfail($id);

        if($user->type == 3)
        {
           if($cashInfo->org_id != $user->org_id)
           {
               return $this->returnJSON(null, 0, '权限错误');
           }
        }elseif($user->type == 4)
        {

        }else{
            throw new \Exception('权限不足');
        }
        $this->validate($request, [
//            'status' => 'required|in:0,1',
            'reason' => $request->get('status') == 2? 'required|max:255':'',
        ]);

        $data = $request->only(['reason']);

        $data['verify_status'] = $request->get('status');
        $data['verify_msg'] = $request->get('reason', '');
//        dd($data);

        $cashInfo->fill($data);
        if($cashInfo->save())
        {
            return $this->returnJSON(null, 0, '修改成功');
        }
        return $this->returnJSON(null, 500, '修改失败');

    }

    public function info(Request $request)
    {
        $user = $request->user();

        if($user->type != 2)
        {
            throw new \Exception('权限不足');
        }

        $node = TeamCashInfo::where('team_id', $user->team_id)->first();
//        dd($node);
        if ($node && isset($node)){
            $node = $node->toArray();
            $node['phone'] = $node['contacts_phone'];
        } else {
            $node = new TeamCashInfo();
            $node->verify_status = null;
        }

        return $this->returnJSON($node, 0, 'ok');
    }

    public function destroy(Request $request, $id)
    {

    }


}
